<template>
  <div class="story-manage-page">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Document /></el-icon>
            <span class="header-title">救助故事管理</span>
          </div>
          <el-button type="primary" @click="openDialog()" :icon="Plus">
            新增故事
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-alert
          v-if="!animalId"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 16px;"
        >
          请先选择动物以查看救助故事
        </el-alert>
        <el-select 
          v-model="animalId" 
          placeholder="选择动物（必选）" 
          filterable
          style="width: 250px;"
          @change="handleAnimalChange"
        >
          <el-option 
            v-for="a in animalList" 
            :key="a.id" 
            :label="`${a.name} (${a.species})`" 
            :value="a.id" 
          />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索标题"
          clearable
          style="max-width: 300px;"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      </div>

      <!-- 表格 -->
      <el-table 
        :data="filteredList" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="photo" label="图片" width="120" align="center">
          <template #default="{ row }">
            <div 
              v-if="row.photo"
              class="image-preview-cell"
              @click="previewStoryImage(row)"
            >
              <el-image
                :src="formatImageUrl(row.photo)"
                fit="cover"
                style="width: 80px; height: 80px; border-radius: 6px; cursor: pointer;"
              />
            </div>
            <span v-else class="no-image">暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="animalName" label="动物昵称" width="150" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="openDialog(row)"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="del(row.id)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty 
        v-if="!loading && filteredList.length === 0" 
        description="暂无数据"
        style="margin: 40px 0;"
      />
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog 
      v-model="visible" 
      :title="form.id ? '编辑故事' : '新增故事'" 
      width="800px"
      @close="handleDialogClose"
    >
      <el-form 
        ref="formRef"
        :model="form" 
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="动物" prop="animalId">
          <el-select 
            v-model="form.animalId" 
            placeholder="请选择动物"
            filterable
            style="width: 100%;"
          >
            <el-option 
              v-for="a in animalList" 
              :key="a.id" 
              :label="`${a.name} (${a.species})`" 
              :value="a.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="form.title" 
            placeholder="请输入故事标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="form.content" 
            type="textarea" 
            :rows="8"
            placeholder="请输入救助故事内容"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="图片">
          <el-upload
            action="http://localhost:8080/api/admin/story/upload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :show-file-list="false"
            accept="image/*"
          >
            <template #trigger>
              <div class="upload-area">
                <img 
                  v-if="form.photo" 
                  :src="formatImageUrl(form.photo)" 
                  class="upload-image"
                />
                <div v-else class="upload-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <div class="upload-text">点击上传</div>
                </div>
              </div>
            </template>
          </el-upload>
          <div class="upload-tip">支持 jpg/png 格式，建议尺寸 800x600</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="save" :loading="saving">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog 
      v-model="imagePreviewVisible" 
      title="图片预览" 
      width="90%"
      class="preview-dialog"
      @closed="handleImagePreviewClosed"
    >
      <div class="preview-container">
        <div class="preview-wrapper">
          <img 
            :src="previewImageUrl" 
            class="preview-image-full"
            alt="预览图片"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Document, Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue';
import axios from "axios";

const list = ref([]);
const visible = ref(false);
const searchKeyword = ref("");
const animalId = ref(null);
const loading = ref(false);
const saving = ref(false);
const form = ref({});
const animalList = ref([]);
const formRef = ref(null);

// 图片预览相关
const imagePreviewVisible = ref(false);
const previewImageUrl = ref('');

const formRules = {
  animalId: [{ required: true, message: '请选择动物', trigger: 'change' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
};

const filteredList = computed(() => {
  if (!searchKeyword.value) {
    return list.value;
  }
  const keyword = searchKeyword.value.toLowerCase();
  return list.value.filter(item => 
    item.title?.toLowerCase().includes(keyword)
  );
});

const formatImageUrl = (url) => {
  if (!url) return '';
  if (url.startsWith('http')) return url;
  if (url.startsWith('/')) return `http://localhost:8080${url}`;
  return `http://localhost:8080/uploads/${url}`;
};

const formatTime = (time) => {
  if (!time) return '-';
  return time;
};

const getAnimalList = async () => {
  try {
    const res = await axios.get("http://localhost:8080/api/admin/animal/list", {
      params: {
        page: 1,
        size: 1000 // 获取足够多的动物列表
      }
    });
    if (res.data.code === 200) {
      animalList.value = res.data.data || [];
    } else {
      ElMessage.error('获取动物列表失败');
    }
  } catch (error) {
    console.error('获取动物列表失败:', error);
    ElMessage.error('获取动物列表失败');
  }
};

const getList = async () => {
  if (!animalId.value) {
    list.value = [];
    return;
  }
  
  loading.value = true;
  try {
    const res = await axios.get("http://localhost:8080/api/admin/story/list", {
      params: { animalId: animalId.value }
    });
    console.log('故事列表API响应:', res.data);
    if (res.data.code === 200) {
      const stories = res.data.data || [];
      // 为每个故事添加动物名称
      list.value = stories.map(story => {
        const animal = animalList.value.find(a => a.id === story.animalId);
        return {
          ...story,
          animalName: animal ? animal.name : '未知动物'
        };
      });
      console.log('加载的故事数据:', list.value);
      if (list.value.length === 0) {
        ElMessage.info('该动物暂无故事记录');
      }
    } else {
      ElMessage.error(res.data.msg || '获取数据失败');
      list.value = [];
    }
  } catch (error) {
    console.error('获取故事列表失败:', error);
    console.error('错误详情:', error.response?.data);
    ElMessage.error('获取数据失败：' + (error.response?.data?.msg || error.message || '未知错误'));
    list.value = [];
  } finally {
    loading.value = false;
  }
};

const openDialog = (row) => {
  if (row) {
    form.value = { ...row };
    // 处理图片URL
    if (form.value.photo && !form.value.photo.startsWith('http')) {
      form.value.photo = formatImageUrl(form.value.photo);
    }
  } else {
    form.value = {
      animalId: null,
      title: '',
      content: '',
      photo: ''
    };
  }
  visible.value = true;
};

const handleDialogClose = () => {
  formRef.value?.resetFields();
  form.value = {};
};

const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    form.value.photo = res.url || res.data?.url || res.data;
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error(res.msg || '图片上传失败');
  }
};

const handleUploadError = () => {
  ElMessage.error('图片上传失败');
};

const save = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息');
      return;
    }
    
      saving.value = true;
    try {
      const isUpdate = form.value.id;
      const url = isUpdate
        ? "http://localhost:8080/api/admin/story/update" 
        : "http://localhost:8080/api/admin/story/add";
      
      const method = isUpdate ? 'put' : 'post';
      const res = await axios[method](url, form.value);
      if (res.data.code === 200) {
        ElMessage.success("保存成功");
        visible.value = false;
        getList();
      } else {
        ElMessage.error(res.data.msg || '保存失败');
      }
    } catch (error) {
      console.error('保存失败:', error);
      ElMessage.error('保存失败');
    } finally {
      saving.value = false;
    }
  });
};

const del = async (id) => {
  try {
    await ElMessageBox.confirm("确定删除该故事吗？", "提示", { 
      type: "warning",
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    });
    
    const res = await axios.delete(`http://localhost:8080/api/admin/story/delete/${id}`);
    if (res.data.code === 200) {
      ElMessage.success("删除成功");
      getList();
    } else {
      ElMessage.error(res.data.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

const handleAnimalChange = () => {
  // 当选择动物变化时，重新加载故事列表
  getList();
};

const handleSearch = () => {
  // 搜索已通过 computed 实现
};

const handleReset = () => {
  animalId.value = null;
  searchKeyword.value = '';
  list.value = [];
};

// 预览故事图片
const previewStoryImage = (row) => {
  if (row.photo) {
    previewImageUrl.value = formatImageUrl(row.photo);
    imagePreviewVisible.value = true;
  }
};

// 关闭图片预览
const handleImagePreviewClosed = () => {
  previewImageUrl.value = '';
};

onMounted(() => {
  getAnimalList();
  // 不自动加载列表，需要先选择动物
});
</script>

<style scoped>
.story-manage-page {
  width: 100%;
}

.main-card {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 22px;
  color: #E6A23C;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.no-image {
  color: #909399;
  font-size: 12px;
}

.image-preview-cell {
  cursor: pointer;
  display: inline-block;
}

.image-preview-cell:hover {
  opacity: 0.8;
}

.upload-area {
  width: 200px;
  height: 150px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  overflow: hidden;
}

.upload-area:hover {
  border-color: #409EFF;
  background: #f5f7fa;
}

.upload-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.upload-icon {
  font-size: 32px;
  color: #8c939d;
}

.upload-text {
  color: #8c939d;
  font-size: 14px;
}

.upload-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>

<!-- 预览对话框样式 -->
<style>
.preview-container {
  background: #1a1a1a;
  border-radius: 8px;
  overflow: hidden;
  padding: 20px;
}

.preview-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

.preview-image-full {
  max-width: 100%;
  max-height: 80vh;
  object-fit: contain;
  border-radius: 8px;
}
</style>